import axios from 'axios'
import { Message } from 'element-ui'

let rootUrl, fileUrl, viewUrl
if (process.env.NODE_ENV == 'production') {
  rootUrl = ''
  fileUrl = ''
  viewUrl = ''
} else {
  rootUrl = '/api/'
  fileUrl = '/api/'
  viewUrl = '/api/'
}

const instance = axios.create({
  baseURL: rootUrl,
  timeout: 1000,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

// axios请求拦截器
instance.interceptors.request.use(config => {
  config.withCredentials = true;
	return config;
},error => {
  Promise.reject(error)
})

// axios响应拦截器
instance.interceptors.response.use(response => {
  if(response.data.type == 'success'){
    return response.data;
  }else{
    Message({
        message: response.data.content,
        type: 'error'
    });
    return Promise.reject(response.data.content);
  }
},error => {
  if(error.message && error.message === '请求重复'){
  }else if(error.response && error.response.status == 401){
    router.replace('/login');
  }
  return Promise.reject(error)
})

export default {
  rootUrl,
  fileUrl,
  viewUrl,
  post: (url,data) => instance.post(url,data),
  get: (url) => instance.get(url)
}
